package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.properties.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * @Auther: xiang
 * @Date: 2019/8/16 16:44
 * @Description:
 */
@Service

public class UploadService {
    //支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg", "image/bmp");
@Autowired
    private OSS client;
@Autowired
     private OSSProperties prop;
    public String upload(MultipartFile file) {
        //图片信息校验
        String contentType = file.getContentType();
        if (!suffixes.contains(contentType)) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //校验图片内容
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
        if (image == null) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);

        }
//保存图片//生成保存目录,保存到nginx所在目录的html下，这样可以直接通过nginx来访问到
        File dir = new File("D:\\nginx-1.12.2\\html\\images");
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            file.transferTo(new File(dir, file.getOriginalFilename()));
            return "http://image.leyou.com/images/" + file.getOriginalFilename();
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 通过配置将上传到阿里云所需要的文件导入
     * @param
     * @return
     */
    public Map<String, Object> getSignature() {
        try {
            //算过期时间 ，这个时间就是浏览器发送token的有效时间，过了时间就这个阿里云就不会接收
            //就是当前时间加上你现在的时间就是这个签名token失效时间。
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            //策略条件，就是上传文件的限制条件
            PolicyConditions policyConds = new PolicyConditions();
            //限制文件大小
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            //限制文件上传的路径
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            //转换限制条件为一个字符串
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            //限制请求为请求字符串，利用base64加密
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            //把限制条件，利用密钥，计算出签名。
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}